package org.csu.jpetstore_user.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.kms.aliyun.http.HttpResponse;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.csu.jpetstore_user.config.AlipayConfig;
import org.csu.jpetstore_user.entity.*;
import org.csu.jpetstore_user.persistence.*;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Controller
//@MapperScan("org.csu.jpetstore_user.persistence")
public class OrderController {

    @Resource
    private AlipayClient alipayClient;
    @Resource
    private AlipayTradePagePayRequest alipayTradePagePayRequest;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderStatusMapper orderStatusMapper;

    @Autowired
    private LineItemMapper lineItemMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ItemMapper itemMapper;


    //我的订单页面
    @GetMapping("/orderList")
    public String orderList(HttpSession session){
        //查询登录用户的订单列表
        User loginUser = (User) session.getAttribute("loginUser");
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("userid",loginUser.getUsername());
        List<Order> orderList = orderMapper.selectList(orderQueryWrapper);
        session.setAttribute("orderList",orderList);
        return "order/orderList";
    }

    //查看具体订单的详细信息
    @GetMapping("/viewOrderForm")
    public String viewOrderForm(HttpSession session,@RequestParam("orderId") int orderId){

        //获取登录用户
        User loginUser = (User) session.getAttribute("loginUser");
        //通过orderId将订单信息放入session中
        this.setOrderDetailsToSession(session,orderId);

        System.out.println("用户："+loginUser.getUsername()+" 查看订单："+orderId);
        return "order/viewOrderForm";
    }

    //产生新订单
    @GetMapping("newOrderForm")
    public String newOrderForm(HttpSession session,@ModelAttribute Order newOrder){

        Account account = (Account) session.getAttribute("account");
        //获得购物车
        Cart cart = (Cart) session.getAttribute("cart");
        if(cart == null){
            cart = new Cart();
            session.setAttribute("cart",cart);
        }
        if(account == null){//用户未登录，请求重定向，产生新的请求，所有资源都将清空
            return "account/signon";
        }else {//用户已登录，则产生新订单
            //产生新order
            newOrder.initOrder(account,cart);
            //数据库中orders表单中加入该订单
            //TODO:此时订单状态为未支付
            orderMapper.insert(newOrder);

            //清除购物车信息
            session.removeAttribute("cart");
            cart = new Cart();
            session.setAttribute("cart",cart);
            //获取数据库最新数据的订单id
            int orderId = orderMapper.getOnly();
            newOrder.setOrderId(orderId);

            session.setAttribute("newOrder",newOrder);

            System.out.println(orderId+" 新订单生成......");
            return "order/newOrderForm";
        }
    }

    //确认并提交订单，返回订单详情页面
    @PostMapping("confirmOrderForm")
    public void confirmOrderForm(HttpSession session, HttpServletResponse response) throws AlipayApiException, IOException {
        Order insertOrder = (Order) session.getAttribute("newOrder");
        int orderId = insertOrder.getOrderId();
        BigDecimal  WIDtotal_amount =  insertOrder.getTotalPrice();//订单总价，即付款金额
        Calendar calendar = new GregorianCalendar();
        String WIDout_trade_no = String.valueOf(calendar.getTimeInMillis());//订单编号
        String WIDsubject = insertOrder.getUsername();//订单名称
        String WIDbody = "OrderId:"+insertOrder.getOrderId()//订单的描述，可以为空
                +"Username:"+insertOrder.getUsername()
                +"BillAdress:"+insertOrder.getBillAddress1()
                +"BillCity"+insertOrder.getBillCity()
                +"BillCountry"+insertOrder.getBillCountry();

        //1.获得初始化的AlipayClient
        //2.设置请求参数AlipayTradePagePayRequest
        alipayTradePagePayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayTradePagePayRequest.setNotifyUrl(AlipayConfig.notify_url);
        alipayTradePagePayRequest.setBizContent("{\"out_trade_no\":\"" + WIDout_trade_no + "\","
                + "\"total_amount\":\"" + WIDtotal_amount + "\","
                + "\"subject\":\"" + WIDsubject + "\","
                + "\"body\":\"" + WIDbody + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = alipayClient.pageExecute(alipayTradePagePayRequest).getBody();
        //输出
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(result);

        //向lineItem表单中加入信息
        List<LineItem> lineItems = insertOrder.getLineItems();
        for (int i = 0; i < lineItems.size(); i++) {
            LineItem lineItem = lineItems.get(i);
            lineItem.setOrderId(orderId);
            lineItem.setLineNumber(i+1);
            System.out.println(lineItem.getOrderId()+" 订单item："+(i+1)+"成功加入lineItem表单.......");
            if(lineItem != null){
                lineItemMapper.insert(lineItem);
            }
            else{
                System.out.println("OrderController:lineItem is null");
            }
        }

        //向orderStatus表单中加入信息
        //TODO:设置订单状态为已支付
        OrderStatus orderStatus = insertOrder.getOrderStatus();
        orderStatus.setOrderid(orderId);
        orderStatus.setLinenum(lineItems.size());
        orderStatusMapper.insert(orderStatus);
        System.out.println(orderStatus.getOrderid()+" 订单成功加入orderStatus表单......");

        //通过orderId将订单信息放入session中
        this.setOrderDetailsToSession(session,orderId);

        System.out.println(orderId+" 订单成功提交......");
//        return "redirect:/viewOrderForm";
    }

    //通过orderId将订单信息放入session中
    public void setOrderDetailsToSession(HttpSession session,int orderId){

        //1、放入order实体
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("orderid",orderId);
        Order order = orderMapper.selectOne(orderQueryWrapper);
        session.setAttribute("order",order);

        //2、放入orderStatus信息
        QueryWrapper<OrderStatus> orderStatusQueryWrapper = new QueryWrapper<>();
        orderStatusQueryWrapper.eq("orderid",orderId);
        OrderStatus orderStatus = orderStatusMapper.selectOne(orderStatusQueryWrapper);
        session.setAttribute("orderStatus",orderStatus);

        //3、放入order中的lineItems
        QueryWrapper<LineItem> lineItemQueryWrapper = new QueryWrapper<>();
        lineItemQueryWrapper.eq("orderid",orderId);

        List<LineItem> lineItems = lineItemMapper.selectList(lineItemQueryWrapper);
        //计算每个lineItem的总价
        for (int i = 0; i < lineItems.size(); i++) {
            LineItem lineItem = lineItems.get(i);
            BigDecimal total = lineItem.getUnitPrice().multiply(new BigDecimal(lineItem.getQuantity()));
            lineItem.setTotal(total);
        }
        session.setAttribute("lineItems",lineItems);

        //3、放入lineItems中包括的items
        List<Item> items = new ArrayList<>();
        QueryWrapper<Item> itemQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        for (int i = 0; i < lineItems.size(); i++) {
            LineItem lineItem = lineItems.get(i);
            String itemId = lineItem.getItemId();
            itemQueryWrapper.eq("itemid",itemId);
            Item item = itemMapper.selectOne(itemQueryWrapper);
            if(item != null){
                //将productName放入item实体中
                productQueryWrapper.eq("productid",item.getProductId());
                String productName = productMapper.selectOne(productQueryWrapper).getName();
                item.setProductName(productName);

                items.add(item);
            }
            else{
                System.out.println("OrderController:item is null");
            }
        }
        session.setAttribute("Items",items);
    }

}
